#include"LinkList.h"

SLK* CreateNode(SListDataType x ) // 创建节点
{
	SLK* NewNode = (SLK*)malloc(sizeof(SLK) * 1);
	assert(NewNode);
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}
void SListPrint(SLK* phead) // 输出数据域
{
	SLK* cur = phead;   // 不改变头节点的指向
	while (cur != NULL)
	{
		printf("%d => ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SListPushBack(SLK** pphead, SListDataType x) // 尾插
{
	SLK * NewNode = CreateNode(x);// 创建节点
	if (*pphead == NULL)
	{
		*pphead  = NewNode;
	}
	else
	{
		SLK* tail = *pphead;
		while (tail->next != NULL)
			tail = tail->next;   // tail 指向-> 尾节点
		tail->next = NewNode;
	}
}

void SListPushFront(SLK** pphead, SListDataType x) // 前推
{
	SLK* NewNode = CreateNode(x); // 创建节点
	NewNode->next = *pphead;
	*pphead = NewNode;
}

void SListPopBack(SLK** pphead)
{
	assert(*pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLK* tail = *pphead;
		SLK* prev = *pphead;
		while (tail->next != NULL)
		{
			// 快慢指针
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;
		prev->next = NULL;
	}
}

void SListPopFront(SLK** pphead) // 头删
{
	assert(*pphead);
	SLK* temp = (*pphead)->next;
	free(*pphead);
	*pphead = temp;
}

SLK* SListFind(SLK* phead, SListDataType x)
{
	assert(phead);//  空链表不需要查了

	SLK* cur = phead;
	while (cur != NULL)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return cur;
}

void SListChange(SLK* pos, SListDataType x)
{
	pos->data = x;
}

void SListInset(SLK** pphead, SLK* pos, SListDataType x)
{
	assert(*pphead);
	assert(pos);

	SLK* NewNode = CreateNode(x);
	NewNode->next = pos;
	if (*pphead == pos)
	{
		*pphead = NewNode;
	}
	else
	{
		SLK* i = *pphead;
		while (i->next != pos)
		{
			i = i->next;
		}
		i->next = NewNode;
	}
}

void SListErase(SLK** pphead, SLK* pos) // 任意位置删除
{
	assert(*pphead);
	assert(pos);
	if ((*pphead) == pos)
	{
		*pphead = pos->next;
	}
	else
	{
		SLK* left = *pphead;
		while (left->next != pos)
			left = left->next;
		left->next = pos->next;
	}
	free(pos);
}

void SListDestory(SLK** pphead)
{
	assert(*pphead);
	SLK* cur = *pphead;
	while (cur)
	{
		SLK* temp = cur->next;
		free(cur);
		cur = temp;
	}
	*pphead = cur;
}

void SListInsetAfter(SLK* phead, SLK* pos, SListDataType x)
{
	SLK * NewNode = CreateNode(x);
	NewNode->next = pos->next;
	pos->next = NewNode;
}

void SListEraseAfter(SLK* pos) // 任意之前位置删除
{
	assert(pos->next);
	SLK* temp = pos->next;
	pos->next = pos->next->next;
	free(temp);
}
